from sqlalchemy import and_, select, update
from forward.dependencies.database import db
from forward.model.schemas.lucky.prize_temp import (
    PrizeTempCreateSchema,
    PrizeTempOutSchema,
)
from forward.model.tables.activity import PrizeTempModel


class PrizeTempORM:

    async def create(self, add_in: PrizeTempCreateSchema):
        pass

    async def get_one_by_id(self, id) -> PrizeTempOutSchema | None:
        statement = select(PrizeTempModel).where(PrizeTempModel.id == id)
        record = await db.fetch_one(statement)
        if not record:
            return None
        return PrizeTempOutSchema.model_validate(record, from_attributes=True)

    async def update(self, id, **kwargs):
        data = {}
        for k, v in kwargs.items():
            if hasattr(PrizeTempModel, k):
                data[k] = v
        statement = update(PrizeTempModel).where(PrizeTempModel.id == id).values(**data)
        id = await db.execute(statement)
        return await self.get_one_by_id(id)

    async def get_all_by_filters(self, **kwargs) -> list[PrizeTempOutSchema]:
        where = []
        for k, v in kwargs.items():
            if hasattr(PrizeTempModel, k):
                where.append(getattr(PrizeTempModel, k) == v)
        user_prize_qrcode_statement = select(PrizeTempModel).where(and_(*where))
        records = await db.fetch_one(user_prize_qrcode_statement)
        if not records:
            return []
        return [
            PrizeTempOutSchema.model_validate(record, from_attributes=True)
            for record in records
        ]
